package com.sun.controller;

import com.sun.pojo.FileUpload;
import com.sun.pojo.User;
import com.sun.service.FileUploadService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Administrator
 */
@Controller
@RequestMapping("/files")
public class FileAllController {

    private final static String BASE_PATH="C:\\Users\\Administrator\\Desktop\\item\\";

    @Autowired
    private FileUpload fileUpload;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 展示文件列表
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/fileAll")
    public String fileAll(HttpSession session, Model model){
        User user = (User)session.getAttribute("user");
        List<FileUpload> fileUploadsList = fileUploadService.findAll(user.getId());
        model.addAttribute("fileUploadsList",fileUploadsList);
        return "/fileAll";
    }

    /**
     * 文件上传：
     * 文件前端传入，后端获取到文件通过输出流写入文件
     * 上传的主要核心是ResourceUtils获取项目的相对路径，然后通过文件的transferTo方法保存到指定路径的文件夹下
     * @param session
     * @param file
     * @param attributes
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(HttpSession session, @RequestParam("file")MultipartFile file, RedirectAttributes attributes) throws IOException {
        System.out.println("准备上传");
        if(file.isEmpty()){
           attributes.addFlashAttribute("msg","上传的文件不能为空");
           return "redirect:/files/fileAll";
        }
        //获取原始文件名称
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String extension = "."+FilenameUtils.getExtension(originalFilename);
        //获取新文件名称 命名：时间戳+UUID+后缀
        String newFileName=LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))+ UUID.randomUUID().toString().substring(0,4)+ extension;
        /*//获取资源路径 classpath的项目路径+/static/files  classpath就是resources的资源路径
        String path = ResourceUtils.getURL("classpath:").getPath() + "static/files/";*/

        //新建一个时间文件夹标识，用来分类
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //全路径(存放资源的路径) 资源路径+时间文件夹标识
        String dataDir = BASE_PATH + format;
        System.out.println(dataDir);
        //全路径存放在文件类中，判断文件夹是否存在不存在就创建
        //也可以直接放进去进行拼接 File dataFile = new File(path,format);
        File dataFile = new File(dataDir);
        if(!dataFile.exists()){
            dataFile.mkdirs();
        }
        //文件上传至指定路径
        file.transferTo(new File(dataFile,newFileName));

        System.out.println("文件上传成功");
        //文件信息保存到数据库
        //获取文件格式
        String type = file.getContentType();
        //获取文件大小
        long size = file.getSize();
        //封装进实体类
        fileUpload.setOldFileName(originalFilename);
        fileUpload.setNewFileName(newFileName);
        fileUpload.setExt(extension);
        fileUpload.setPath(dataDir+"\\"+newFileName);
        fileUpload.setGlobalPath(dataDir);
        fileUpload.setDownCounts(0);
        fileUpload.setType(type);
        fileUpload.setSize(size);
        fileUpload.setUploadTime(new Date());
        User user = (User)session.getAttribute("user");
        fileUpload.setUserId(user.getId());
        //检测字符串是否以指定的前缀开始
        boolean img = type.startsWith("image");
        fileUpload.setIsImg(img?"是":"否");
        System.out.println(fileUpload);
        int result= fileUploadService.saveFile(fileUpload);
        System.out.println("保存结果："+result);
        attributes.addFlashAttribute("msg",result==1?"保存成功":"保存失败！");
        System.out.println("上传结束");
        return "redirect:/files/fileAll";
    }

    /**
     * 下载：获取到文件路径，通过输入流读取，再获取响应输出流，通过工具类中的拷贝方法IOUtils.copy()实现在线打开，通过附件形式实现文件下载。
     * （前提是需要依赖包才能使用IOUtils工具类）
     * @param id
     * @param openStyle
     * @param response
     */
    @GetMapping("/download")
    public void download(Integer id, String openStyle, HttpServletResponse response) throws IOException {
        FileUpload fileUpload=fileUploadService.findFileById(id);
        //获取全路径
        //String globalPath = ResourceUtils.getURL("classpath:").getPath() + "static" + fileUpload.getPath() + "/";
        String globalPath = fileUpload.getGlobalPath();
        System.out.println("文件所在全路径："+globalPath);
        FileInputStream inputStream = new FileInputStream(new File(globalPath, fileUpload.getNewFileName()));
        /**
         * 点击会提供对话框选择另存为： response.setHeader( “Content-Disposition “,“attachment;filename= “+filename);
         * 通过IE浏览器直接选择相关应用程序插件打开： response.setHeader( “Content-Disposition “,“inline;filename= “+fliename)
         * 下载前询问（是打开文件还是保存到计算机） response.setHeader( “Content-Disposition “,“filename= “+filename);
         */
        //根据传过来的参数判断是下载，还是在线打开
        if("attachment".equals(openStyle)){
            //并更新下载次数
            fileUpload.setDownCounts(fileUpload.getDownCounts()+1);
            fileUploadService.updateFileDownCounts(id,fileUpload.getDownCounts());
            //以附件形式下载  点击会提供对话框选择另存为：
            response.setHeader( "Content-Disposition","attachment;filename="+ URLEncoder.encode(fileUpload.getOldFileName(),"utf8"));
        }
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //利用IO流工具类实现流文件的拷贝，（输出显示在浏览器上在线打开方式）
        IOUtils.copy(inputStream,outputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }

    /**
     * 删除文件：先删除文件再删数据库中的信息
     * @param id 文件id
     * @param attributes attributes
     * @return
     * @throws FileNotFoundException
     */
    @GetMapping("/delete")
    public String delete(Integer id, RedirectAttributes attributes) throws FileNotFoundException {
        FileUpload fileUpload = fileUploadService.findFileById(id);
        System.out.println("根据id查询到：" + fileUpload);
        //根据数据库的信息拼接文件的全路径  资源路径+static+数据库已存入的文件路径+"/"+新文件名
        //如：D:/IDEAworkspace/3SpringBoot_Workspace/functionDemo/FileUploadDemo01/target/classes/static/files/2020-11-03/
        //String globalPath = ResourceUtils.getURL("classpath:").getPath() + "static" + fileUpload.getPath() + "/";
        String globalPath = fileUpload.getGlobalPath();
        System.out.println(globalPath);
        File file = new File(globalPath, fileUpload.getNewFileName());
        if(file.exists() && file.isFile()){
            file.delete();
        }
        int b = fileUploadService.deleteFileById(id);
        if(b == 1){
            attributes.addFlashAttribute("msg","删除成功！");
        }else{
            attributes.addFlashAttribute("msg", "删除失败！");
        }
        return "redirect:/files/fileAll";
    }
}
